package com.meis.widget.radius;

import com.meis.widget.radius.delegate.RadiusViewDelegate;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.app.Context;

/**
 * @Author: AriesHoo on 2018/7/19 10:06
 * @E-Mail: AriesHoo@126.com
 * Function:用于需要圆角矩形框背景的RelativeLayout的情况,减少直接使用RelativeLayout时引入的shape资源文件
 * Description:
 */
public class RadiusRelativeLayout extends DependentLayout implements Component.EstimateSizeListener, ComponentContainer.ArrangeListener {
    private RadiusViewDelegate delegate;

    public RadiusRelativeLayout(Context context) {
        this(context, null);
    }

    public RadiusRelativeLayout(Context context, AttrSet attrs) {
        super(context, attrs);
        delegate = new RadiusViewDelegate(this, context, attrs);
        setEstimateSizeListener(this::onEstimateSize);
        setArrangeListener(this::onArrange);
        init();
    }
    private void init(){
        if (delegate == null) {
            return ;
        }
        getContext().getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                if (delegate.getRadiusHalfHeightEnable()) {
                    delegate.setRadius(getEstimatedHeight() / (float) 2);
                }
                delegate.init();
            }
        }, 10);
    }
    /**
     * 获取代理类用于Java代码控制shape属性
     *
     * @return RadiusViewDelegate
     */
    public RadiusViewDelegate getDelegate() {
        return delegate;
    }




    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
        if (delegate != null) {
            delegate.setSelected(selected);
        }
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {
        if (delegate == null) {
            return true;
        }
        setEstimatedSize(Component.EstimateSpec.getSize(i), Component.EstimateSpec.getSize(i1));
        if (delegate.getWidthHeightEqualEnable() && getEstimatedWidth() > 0 && getEstimatedHeight() > 0) {
            int max = Math.max(getEstimatedWidth(), getEstimatedHeight());
            int measureSpec = Component.EstimateSpec.getSizeWithMode(max, Component.EstimateSpec.PRECISE);
            super.estimateSize(measureSpec, measureSpec);
        }
        /*if (delegate.getRadiusHalfHeightEnable()) {
            delegate.setRadius(getEstimatedHeight() / 2);
        }*/
       // delegate.init();
        return false;
    }

    @Override
    public boolean onArrange(int i, int i1, int i2, int i3) {
        if (delegate != null) {
            if (delegate.getRadiusHalfHeightEnable()) {
                delegate.setRadius(getHeight() / (float) 2);
            }
            delegate.init();
        }
        return false;
    }

}
